#include "../include/TexturedNode.hpp"
#include "../include/Utils.hpp"
using namespace klas;

#include <iostream>
using namespace std;

TexturedNode::TexturedNode()
{
	m_tex = NULL;
	m_rot = 0.0;
	m_scale = 1.0;
	m_ID = INVALID_ID;
	m_shouldRender = false;
}

TexturedNode::TexturedNode(DataObject* tex)
{
	setTexture(tex);
	m_rot = 0.0;
	m_scale = 1.0;
	m_ID = INVALID_ID;
}

TexturedNode* TexturedNode::getDeepCopy()
{
	
	TexturedNode* node = new TexturedNode();
	node->m_rot = m_rot;
	node->m_scale = m_scale;
	node->m_ID = m_ID;
	node->m_rect.setPos(m_rect.getPos());
	node->m_rect.setDim(m_rect.getDim());
	node->m_prevRect.setPos(m_prevRect.getPos());
	node->m_prevRect.setDim(m_prevRect.getDim());
	node->m_tex = m_tex;
	node->m_baseColor = m_baseColor;
	
	return node;
}


TexturedNode::~TexturedNode()
{
	m_tex = NULL;
}

void TexturedNode::setTexture(DataObject* tex)
{
  if(tex->getObjectType() == Data::TEXTURE)
  {
    m_tex = reinterpret_cast<Texture*>(tex);
    m_rect.w = m_tex->getOrigDim().x;
    m_rect.h = m_tex->getOrigDim().y;
    m_shouldRender = true;
  }
  else
    m_shouldRender = false;
}

void Rotate2D(float angle, float pointOfRotationX, float pointOfRotationY)
{
	// Note that the steps here are in the reverse order of that mentioned above!!
	// That's because openGL transformations post-multiply the matrices.
	glTranslatef(pointOfRotationX, pointOfRotationY, 0.0f);
	glRotatef(angle, 0.0f, 0.0f, 1.0f);
	glTranslatef(-pointOfRotationX, -pointOfRotationY, 0.0f);
}

void TexturedNode::render(const Rectangle<Real>& camera)
{
  if(m_shouldRender == false)
    return;
    
	glPushMatrix();
	glLoadIdentity();
	
	// Rotate the node and position it.
	Rotate2D(m_rot, (m_rect.x - camera.x), (m_rect.y - camera.y));	
	glTranslatef((m_rect.x - ((m_tex->getPaddedDim().x * m_scale) / 2.0) - camera.x), (m_rect.y - ((m_tex->getPaddedDim().y * m_scale) / 2.0) - camera.y), 0.0f);
		
	// Scale the node.
	glScaled(m_scale, m_scale, 0.0);
	
	// Render it!
	glColor4f(m_baseColor.getR(), m_baseColor.getG(), m_baseColor.getB(), m_baseColor.getA());
	glCallList(m_tex->getDisplayListID());
	
	glPopMatrix();
}

iReal TexturedNode::getNodeType() const
{
	return Node::TEXTURE;
}
